package cn.com.nes.common.util;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.GenericResult;
import com.aliyun.oss.model.ProcessObjectRequest;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ShenWei
 * @Date: 2024/03/08/13:55
 */
public class OssImagePathUtils {

    public static String getImgSignURL(String imagePath, int isYs, String endpoint, String accessKeyId,
                                       String accessKeySecret, String bucketName) {

        OSSClient ossClient = null;
        String urlStr = "";
        try {
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            Date expiration = new Date(System.currentTimeMillis() + 5 * 60 * 1000);
            boolean found = ossClient.doesObjectExist(bucketName, imagePath);
            if (found) {
                boolean isImage = DBUtil.isPicture(imagePath);
                if (isImage) {
                    GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, imagePath, HttpMethod.GET);
                    req.setExpiration(expiration);
                    String style = "";
                    switch (isYs) {
                        case 1:
                            style = "image/resize,m_lfit,w_110";
                            break;
                        case 2:
                            style = "image/quality,q_100 ";
                            break;
                        default:
                            break;
                    }
                    if (!"".equals(style)) {
                        req.setProcess(style);
                    }
                    req.addQueryParameter("t", String.valueOf(System.currentTimeMillis()));
                    URL signedUrl = ossClient.generatePresignedUrl(req);
                    urlStr = signedUrl.toString();
                } else {
                    throw new Exception("不是图片");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return urlStr;
    }
    /**
     * 获取该图片的真实地址
     * @param imagePath
     * @param isYs
     * @param endpoint
     * @param accessKeyId
     * @param accessKeySecret
     * @param bucketName
     * @param flag  是否长时间  1为长时间  其他为短时间
     * @return
     */
    public static String getImgSignURL(String imagePath , int isYs,String endpoint,String accessKeyId,
                                       String accessKeySecret,String bucketName,int flag){
        //oss客户端
        OSSClient ossClient = null;
        String urlStr = "";
        try {
            //创建客户端对象
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            Date expiration;
            if(flag==1) {
                //定义过期时间
                expiration  = new Date(System.currentTimeMillis() +  10*365*24*60 * 60 * 1000);
            }else{
                expiration = new Date(System.currentTimeMillis() + 5 * 60 * 1000);
            }
            if (StrUtil.isNotBlank(imagePath)) {
                //判断文件是否存在
                boolean found = ossClient.doesObjectExist(bucketName, imagePath);
                if(!found){
                    bucketName = "nesctce";
                    found = ossClient.doesObjectExist("nesctce", imagePath);
                }
                if (found) {
                    //判断是否为图片
                    boolean isImage = DBUitl.isPicture(imagePath);
                    if (isImage) {
                        //生成签名以后的URL
                        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, imagePath, HttpMethod.GET);
                        //设置过期时间
                        req.setExpiration(expiration);
                        String style = "";
                        //判断是否压缩,1-压缩;2-大图
                        switch (isYs) {
                            case 1:
                                style = "image/resize,m_lfit,w_300/auto-orient,0";
                                break;
                            case 2:
                                style = "image/resize,m_lfit,w_1920,h_1920/auto-orient,0";
                                break;
                            default:
                                break;
                        }
                        if (!"".equals(style)) {
                            //设置图片样式
                            req.setProcess(style);
                        }
                        req.addQueryParameter("t", String.valueOf(System.currentTimeMillis()));
                        //获取图片地址
                        URL signedUrl = ossClient.generatePresignedUrl(req);
                        urlStr = signedUrl.toString();
                    } else {
                        throw new Exception("不是图片");
                    }
                }
            }else{
                throw  new  Exception("图片地址为空");
            }
        } catch(Exception e){
            ;
        } finally{
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return urlStr;
    }



    /**
     * 传用";"拼的图片地址 进行处理返回图片真实地址集合
     * @param imagePathS
     * @param isYs
     * @param endpoint
     * @param accessKeyId
     * @param accessKeySecret
     * @param bucketName
     * @return
     */
    public static List<String> getSomeImgSignURL(String imagePathS , int isYs, String endpoint, String accessKeyId,
                                                 String accessKeySecret, String bucketName){
        List<String> images = new ArrayList<>();
        //判断图片不为空
        if(StrUtil.isNotBlank(imagePathS)){
            //以;分割字符串
            String[] imageSplit = imagePathS.split(";");
            //判断数组不为空
            if(ArrayUtil.isNotEmpty(imageSplit)){
                for(int i=0;i<imageSplit.length;i++){
                    if(StrUtil.isNotBlank(imageSplit[i])) {
                        //获取图片真实地址
                        if(imageSplit[i].indexOf("sjt/") != -1 || imageSplit[i].indexOf("pmt/") != -1 ||
                                imageSplit[i].indexOf("azt/") != -1){
                            bucketName = "nesctce";
                        }
                        String imageUrl = getImgSignURL(imageSplit[i], isYs, endpoint, accessKeyId, accessKeySecret, bucketName, 0);
                        //封装数据
                        images.add(imageUrl);
                    }
                }
            }
        }
        return   images;
    }

    /**
     * 获取文件的真实地址
     * @param filePath
     * @param endpoint
     * @param accessKeyId
     * @param accessKeySecret
     * @param bucketName
     * @return
     */
    public static String getFileSignURL(String filePath ,String endpoint,String accessKeyId,
                                        String accessKeySecret,String bucketName){
        //oss客户端
        OSSClient ossClient = null;
        String urlStr = "";
        try {
            //创建oss客户端
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            //定义过期时间
            Date expiration = new Date(System.currentTimeMillis() + 5 * 60 * 1000);
            //判断文件是否存在
            boolean found = ossClient.doesObjectExist(bucketName,filePath );
            if (found) {
                //生成签名以后的URL
                GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName,filePath, HttpMethod.GET);
                //
                req.setExpiration(expiration);
                req.addQueryParameter("t", String.valueOf(System.currentTimeMillis()));
                URL signedUrl = ossClient.generatePresignedUrl(req);
                urlStr = signedUrl.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return   urlStr;
    }

    /**
     * 添加图片
     * @param objName
     * @param is
     * @param endpoint
     * @param accessKeyId
     * @param accessKeySecret
     * @param bucketName
     * @return
     */
    public static String addPicPObj(String objName, InputStream is,
                                    String endpoint, String accessKeyId, String accessKeySecret,
                                    String bucketName){
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            try {
                ossClient.putObject(bucketName, objName, is);
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (OSSException | com.aliyun.oss.ClientException e) {
                e.printStackTrace();
                System.out.println("添加object\t" + objName + "\t异常。");
                return null;
            }
            return "https://" + bucketName + "." + endpoint + "/" + objName;

        } catch (com.aliyun.oss.ClientException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return null;
    }


    public static String makeObjName1(String prefix, String suffix) {
        return prefix + "/" + System.currentTimeMillis() + "." + suffix;
    }


    public static String getImgSignUrlWithWatermark(String imagePath, int isYs, String endpoint, String accessKeyId,
                                                    String accessKeySecret, String bucketName, int flag,
                                                    String location, String time) {
        //oss客户端
        OSSClient ossClient = null;
        String urlStr = "";
        try {
            //创建客户端对象
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            Date expiration;
            if(flag==1) {
                //定义过期时间
                expiration  = new Date(System.currentTimeMillis() +  10*365*24*60 * 60 * 1000);
            }else{
                expiration = new Date(System.currentTimeMillis() + 5 * 60 * 1000);
            }
            if (StrUtil.isNotBlank(imagePath)) {
                //判断文件是否存在
                boolean found = ossClient.doesObjectExist(bucketName, imagePath);
                if(!found){
                    bucketName = "nesctce";
                    found = ossClient.doesObjectExist("nesctce", imagePath);
                }
                if (found) {
                    //判断是否为图片
                    boolean isImage = DBUitl.isPicture(imagePath);
                    if (isImage) {
                        //生成签名以后的URL
                        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, imagePath, HttpMethod.GET);
                        //设置过期时间
                        req.setExpiration(expiration);
                        StringBuilder style = new StringBuilder();
                        //判断是否压缩,1-压缩;2-大图
                        switch (isYs) {
                            case 1:
                                style.append("image/resize,m_lfit,w_300/auto-orient,0");
                                break;
                            case 2:
                                style.append("image/resize,m_lfit,w_1920,h_1920/auto-orient,0");
                                break;
                            default:
                                break;
                        }
                        final int length = location.length();
                        String[] locations = new String[(int) Math.ceil(length / 21.0)];
                        for (int i = 0; i < length; i = i + 21) {
                            String subStr = location.substring(i, Math.min(location.length(), i + 21));
                            String locationBASE64 = Base64.getEncoder().encodeToString(subStr.getBytes());
                            locationBASE64 = locationBASE64.replace("+", "-")
                                    .replace("/", "_");
                            if (locationBASE64.charAt(locationBASE64.length() - 1) == '=') {
                                locationBASE64 = locationBASE64.substring(0, locationBASE64.length() - 2);
                            }
                            locations[i / 21] = locationBASE64;
                        }
                        String timeBASE64 = Base64.getEncoder().encodeToString(time.getBytes());
                        //添加水印
                        for (int i = 0; i < locations.length; i++) {
                            style.append("/watermark,type_ZmFuZ3poZW5naGVpdGk,size_50,text_")
                                    .append(locations[i])
                                    .append(",color_ffffff,shadow_80,t_85,g_se,x_10,y_")
                                    .append((locations.length - i) * 60 + 10);
                        }
                        style.append("/watermark,type_ZmFuZ3poZW5naGVpdGk,size_50,text_")
                                .append(timeBASE64)
                                .append(",color_ffffff,shadow_80,t_85,g_se,x_10,y_10");
                        if (!"".equals(style.toString())) {
                            //设置图片样式
                            req.setProcess(style.toString());
                        }
                        req.addQueryParameter("t", String.valueOf(System.currentTimeMillis()));
                        //获取图片地址
                        URL signedUrl = ossClient.generatePresignedUrl(req);
                        urlStr = signedUrl.toString();
                    } else {
                        throw new Exception("不是图片");
                    }
                }
            }else{
                throw  new  Exception("图片地址为空");
            }
        } catch(Exception e){
            e.printStackTrace();
        } finally{
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return urlStr;
    }

    public static String watermark(String endpoint,String accessKeyId,String accessKeySecret,
                                   String bucketName, String sourceImage) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 添加水印
            StringBuilder sbStyle = new StringBuilder();
            Formatter styleFormatter = new Formatter(sbStyle);
            String styleType = "image/watermark,type_d3F5LXplbmhlaQ,size_30,text_SGVsbG8gV29ybGQ,color_FFFFFF,shadow_50,t_100,g_se,x_10,y_10";
            // 将处理后的图片命名为example-watermark.png并保存到当前Bucket。
            // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
            int dotIndex = sourceImage.lastIndexOf(".");
            String targetImage = sourceImage.substring(0, dotIndex) + "-watermark." + sourceImage.substring(dotIndex + 1);
            styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
                    BinaryUtil.toBase64String(targetImage.getBytes()),
                    BinaryUtil.toBase64String(bucketName.getBytes()));
            System.out.println(sbStyle.toString());
            ProcessObjectRequest request = new ProcessObjectRequest(bucketName, sourceImage, sbStyle.toString());
            GenericResult processResult = ossClient.processObject(request);
            String json = IOUtils.readStreamAsString(processResult.getResponse().getContent(), "UTF-8");
            processResult.getResponse().getContent().close();
            System.out.println(json);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return null;
    }

    public static void main(String[] args) {
        final String imagePath = "manufacturerVendor/13096624167/1657183944885.jpg";
        String url = OssImagePathUtils.getImgSignUrlWithWatermark(imagePath, 2, "https://oss-cn-beijing.aliyuncs.com",
                "LTAI4G6G4NCV9Ugb91dx4L5k", "3XQv39bUFNA5DMA6cLp55temmEzNYx",
                "nesmtpf", 0, "山西省临汾市洪洞县341国道爱玛电动车", "2022-01-01 00:00:00");
        System.out.println(url);
    }
}
